import { createRouter, createWebHashHistory } from 'vue-router'
import { localCache } from '@/utils/cache'
import { LOGIN_TOKEN } from '@/global/constants'
import { firstMenu } from '@/utils/map-menus'

const router = createRouter({
  history: createWebHashHistory(),
  routes: [
    {
      path: '/',
      redirect: '/login'
    },
    {
      path: '/login',
      component: () => import('@/views/login/Login.vue')
    },
    {
      path: '/main',
      name: 'main',
      component: () => import('@/views/main/Main.vue')
      // children: [
      //   {
      //     path: '/main/analysis/overview',
      //     component: () => import('@/views/main/analysis/overview/overview.vue')
      //   },
      //   {
      //     path: '/main/analysis/dashboard',
      //     component: () => import('@/views/main/analysis/dashboard/dashboard.vue')
      //   },
      //   {
      //     path: '/main/system/user',
      //     component: () => import('@/views/main/system/user/user.vue')
      //   },
      //   {
      //     path: '/main/system/role',
      //     component: () => import('@/views/main/system/role/role.vue')
      //   }
      // ]
    },
    {
      path: '/:pathMatch(.*)*',
      component: () => import('@/views/not-found/NotFound.vue')
    }
  ]
})

// 路由守卫
router.beforeEach((to, from, next) => {
  // console.log('进入路由守卫', to, from)
  const token = localCache.getCache(LOGIN_TOKEN)
  //to and from are Route Object,next() must be called to resolve the hook}
  if (!token) {
    if (to.path !== '/login') {
      next('/login')
    } else {
      next()
    }
  } else {
    if (to.path === '/main' || to.path === '/login') {
      next(firstMenu.url)
    } else {
      next()
    }
  }
})

export default router
